const { Op } = require("sequelize");
const Sequelize = require('sequelize');
const brannerModel = appRequire('models/branner');
const artPPTModel = appRequire('models/artPPT');
const contentImageModel = appRequire('models/contentImage');


// 导出对象，供其它模块调用
module.exports = {
    todayQd,
};

async function todayQd(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ["uid"], request);
    if (checkResult == false) return;

    let nowDay = dateFormat(new Date().getTime(), 'yyyy-mm-dd')

    let todayBranner = await brannerModel.todayBranner.findOne({
        where: {
            time: nowDay + " 08:00:00"
        },
        include: ["artPPT"]
    })
    todayBranner = Common.clone(todayBranner)

    if (!todayBranner) {
        let num1 = randomNum(1, 15)
        let num2 = randomNum(1, 20)

        let pptDet = await artPPTModel.findOne({
            where: {
                fileType: "课件",
                sourceFrom: { [Op.ne]: "创意少儿美术馆" },
                status: 1
            },
            order: [
                [Sequelize.literal('RAND()')]
            ],
        })

        todayBranner = await brannerModel.todayBranner.create({
            objectId: sid.uuid(),
            title: nowDay,
            time: nowDay + " 08:00:00",
            image: "https://qiniu.jimuzhou.cloud/dayQd/" + num1 + "/" + num2 + ".jpg",
            artpptId: pptDet.objectId
        })
    }

    let contentImage = await contentImageModel.findOne({
        where: {
        },
        order: [
            [Sequelize.literal('RAND()')]
        ],
    })

    let todayQd = await brannerModel.todayQd.findOne({
        where: {
            userId: postData.uid,
            bannerId: todayBranner.objectId
        }
    })
    todayQd = Common.clone(todayQd)
    if (todayQd) {
        returnData.data = {
            checked: false,
            todayBranner: todayBranner,
            content: contentImage.content
        }
    } else {
        let todayQd = await brannerModel.todayQd.create({
            objectId: sid.uuid(),
            userId: postData.uid,
            bannerId: todayBranner.objectId,
        })
        returnData.data = {
            checked: true,
            todayBranner: todayBranner,
            content: contentImage.content
        }
    }
    return request.json(returnData)
}


function randomNum(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + 1
}